package com.dingpeikeji.quickdeer.mobile.service;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
public class ImageUpload {
	// 修改用户的图片
	public static String changeUserImage(HttpServletRequest request, HttpServletResponse response,String userid) 
	        throws  Exception {
		String message = "";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //文件保存目录路径
        String savePath = "C:\\images\\userfiles\\userimage\\";
        //检查目录
        File uploadDir = new File(savePath);
        //如果不存在，创建文件夹
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        //此处是直接采用Spring的上传
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileFullname = mf.getOriginalFilename();
            //检查扩展名
            String fileExt = fileFullname.substring(fileFullname.lastIndexOf(".") + 1).toLowerCase();
            String newFileName = userid + "." + fileExt;
            File uploadFile = new File(savePath + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                message = "文件上传成功";
                //数据库保存上传路径
                String saveUserImagePath = "/userfiles/userimage/"+newFileName;
            } catch (IOException e) {
            	message = "文件上传失败";
            }
        }
		return message;
    }
}
